
const tiUserName = 'maze@thunderchip.com';
const tiPassWord = 'Zxc13632671185';


const {
    logger,
    sleep,
    lpop,
    get,
    initPage,
    initPage2,
    closeBrowser,
    randBetween,
} = require('./util');

process.on('unhandledRejection', error => {
    logger('unhandledRejection', error);
});

const mouseMoveAndClick = async (page, selector) => {
    let targetInput;
    if (typeof selector == 'string') {
        targetInput = await page.$(selector);
    } else {
        targetInput = selector;
    }
    const box = await targetInput.boundingBox();
    const x = box.x + (box.width/2) - 3;
    const y = box.y + (box.height/2) - 2;
    await page.mouse.move(x, y, {steps:80});
    await page.mouse.click(x, y, {delay:100});
}

const $mouseMoveAndClick = async (page, selector, index) => {
    let targetInputs;
    if (typeof selector == 'string') {
        targetInputs = await page.$$(selector);
    } else {
        targetInputs = selector;
    }
    const targetInput = targetInputs[index];
    const box = await targetInput.boundingBox();
    const x = box.x + (box.width/2) - 3;
    const y = box.y + (box.height/2) - 2;
    await page.mouse.move(x, y, {steps:80});
    await page.mouse.click(x, y, {delay:100});
}

//用于探测进程是否卡住
let timer = 0;

const $logger = function() {
	logger(...arguments);
    timer = new Date().getTime();
};

//检测进程是否卡住了
(async () => {
    while (1) {
        if (timer > 0 && (new Date().getTime()) - timer > 300000) {
            logger('检测到进程卡住，尝试关闭浏览器');
            await closeBrowser();
            $logger('已关闭浏览器');
        }
        await sleep(10000);
    }
})();

//下单流程
(async () => {
    logger('开始');

    while (1) {
        //启动puppeteer
        $logger('启动浏览器');
        const page = await initPage2();

        //登录
        $logger('登录流程');
        await page.goto('https://www.ti.com.cn/secure-link-forward/?gotoUrl=https%3A%2F%2Fwww.ti.com.cn%2F');
        await page.waitForSelector('input.u-width-full', {timeout: 50000});

        const check = await page.$('input.u-width-full');
        if (check) {
            $logger('输入帐号');
            await mouseMoveAndClick(page, 'input.u-width-full');
            await page.type('input.u-width-full', tiUserName, { delay: 100 });
            await mouseMoveAndClick(page, '#nextbutton');
            await page.waitForTimeout(2000);

            //输入密码
            $logger('输入密码');
            await mouseMoveAndClick(page, 'input[name=password]');
            await page.type('input[name=password]', tiPassWord, { delay: 100 });
            await mouseMoveAndClick(page, '#loginbutton');

            $logger('等待登录结果');
            try {
                await page.waitForSelector('#homepage-carousel', {
                    timeout: 40000,
                });
            } catch(e) {
                $logger('登录失败');
                continue;
            }
            $logger('登录成功');
        } else {
            $logger('已登录，跳过');
        }

        while (1) {
            let cartCount;
            try {
                //检测当前页面域名是否www.ti.com.cn，不是则跳转
                const domain = await page.evaluate(() => {
                    return document.domain;
                });
                if (domain != 'www.ti.com.cn') {
                    await page.goto('https://www.ti.com.cn/');
                }

                //检测页面的购物车篮里是否有商品
                await page.waitForSelector('.ti_p-responsiveHeader-cart-count', {
                    timeout: 30000,
                });
                cartCount = await page.evaluate(() => {
                    return document.querySelector('.ti_p-responsiveHeader-cart-count').innerText;
                });
                if (cartCount == '0') {
                    $logger('购物车空');
                    await sleep(1000);
                    continue;
                }
            } catch(e) {
                $logger('出错', e);
                continue;
            }

            try {
                $logger('进入购物车');
                const url = await page.evaluate(() => {
                    return location.href;
                });
                if (url.indexOf('https://www.ti.com.cn/store/ti/zh/cart') < 0) {
                    await page.goto('https://www.ti.com.cn/store/ti/zh/cart');
                    //可能会进入一个60秒左右的转圈圈，所以这里等久一些
                    await page.waitForSelector('th.order_total', {
                        timeout: 80000
                    });
                    await sleep(10000);
                }

                //选择人民币
                $logger('检测是否人民币');
                const txt = await page.evaluate(() => document.querySelector('th.order_total').innerText);
                if (txt.indexOf('CNY') < 0) {
                    $logger('不是人民币，需要选择人民币');
                    //这里可能还会再等一轮转圈圈
                    await page.waitForFunction(() => {
                        return (
                            document.querySelector("#tiResponsiveHeader ti-header-currency-selection") &&
                            document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot &&
                            document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel") &&
                            document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel").shadowRoot &&
                            document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel").shadowRoot.querySelector(".ti-dropdown-panel-trigger")
                        );
                    }, {
                        timeout: 80000
                    });

                    //如果出现地址和货币选择浮层
                    let skip = 0;
                    const countryLen = await page.evaluate(() => {
                        return document.querySelector('#llc-cartpage-ship-to-country') && document.querySelector('#llc-cartpage-ship-to-country') && document.querySelector('#llc-cartpage-ship-to-country').options && document.querySelector('#llc-cartpage-ship-to-country').options.length;
                    });
                    if (countryLen && countryLen > 10) {
                        $logger('浮层选择货币');
                        await page.evaluate(() => {
                            $('#llc-cartpage-ship-to-country').val('CN').change();
                        });
                        await mouseMoveAndClick(page, '#llc-cartpage-ship-to-continue');
                        skip = 1;
                        await sleep(30000);
                    }

                    if (!skip) {
                        $logger('点击下拉框');
                        const dropdown = await page.evaluateHandle(() => {
                            return document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel").shadowRoot.querySelector(".ti-dropdown-panel-trigger");
                        });
                        await mouseMoveAndClick(page, dropdown);
                        await sleep(1000);
    
                        $logger('选择CNY');
                        const cny = await page.evaluateHandle(() => {
                            return document.querySelector("#tiResponsiveHeader ti-header-currency-selection").shadowRoot.querySelector("ti-dropdown-panel li[data-value=\"CNY\"] a");
                        });
                        await mouseMoveAndClick(page, cny);
                        await sleep(1000);
    
                        $logger('等待页面跳转');
                        await page.waitForFunction(() => {
                            return document.querySelector('th.order_total') && document.querySelector('th.order_total').innerText.indexOf('CNY') > -1;
                        }, {
                            timeout: 40000
                        });
                    }
                }
            } catch(e) {
                $logger('出错', e);
                await sleep(5000);
                continue;
            }

            $logger('开始下单流程，购物车商品数量：', cartCount);

            try {
                //随机移动鼠标
                const x = 10 + randBetween(100, 1700);
                const y = 110 + randBetween(200, 800);
                await page.mouse.move(x, y, {steps:80});

                //打开第一个支付页面
                await page.goto('https://www.ti.com.cn/store/ti/zh/cart/checkout');
                await page.waitForSelector('.addressType', {
                    timeout: 30000,
                });
                $logger('进入支付页成功');
                await page.waitForTimeout(2000);
                await mouseMoveAndClick(page, '.addressType');
                for (let i=0; i<5; i++) {//等待按钮变红
                    const check = await page.$('.ti-button-disabled');
                    if (check) {
                        await sleep(2000);
                    }
                }
                $logger('下一步1');
                await mouseMoveAndClick(page, '#paid-shipping-address-select');
                $logger('等待页面跳转...');
                await page.waitForSelector('#cmpCheckboxflag', {
                    timeout: 30000
                });

                //打开确认发票页
                await page.waitForTimeout(4000);
                $logger('进入发票确认页成功');
                await mouseMoveAndClick(page, '#cmpCheckboxflag');
                $logger('下一步2');
                await mouseMoveAndClick(page, '#tax-invoice-submit');
                $logger('确认发票并继续');
                await $mouseMoveAndClick(page, '.vat-modal-button', 1);
                $logger('等待页面跳转...');
                await page.waitForSelector('#regulations-select', {
                    timeout: 30000
                });

                //打开选择页
                await page.waitForTimeout(4000);
                $logger('进入合规页面成功');
                const waiverAccept = await page.$('#waiver_accept');
                if (waiverAccept) {
                    await mouseMoveAndClick(page, '#waiver_accept');
                }
                await page.evaluate(async () => {
                    $('#regulations-select').val('游戏').change();
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    $('#checkout-regulations-select').val('游戏控制器和外设').change();
                });
                await $mouseMoveAndClick(page, '.militoryRadio', 1);
                await sleep(1000);
                await $mouseMoveAndClick(page, '.militoryRadio', 1);
                await sleep(1000);
                $logger('等待按钮可点');
                //等待按钮变红
                for (let i=0; i<5; i++) {
                    const check = await page.$('.ti-button-disabled');
                    if (check) {
                        await sleep(3000);
                    }
                }
                $logger('下一步3');
                await mouseMoveAndClick(page, '#regulations-submit-btn');
                $logger('等待页面跳转...');
                await page.waitForSelector('.js-checkout-toc-radio', {
                    timeout: 30000
                });

                //运费页
                await page.waitForTimeout(4000);
                $logger('进入运费页面成功');
                await page.evaluate(async () => {
                    $('.js-checkout-toc-radio').prop("disabled", false);
                    $('.toc-lbl-disabled').each(function() {
                        $(this).removeClass('toc-lbl-disabled');
                    });
                    await new Promise(resolve => setTimeout(resolve, 1000));
                });
                await mouseMoveAndClick(page, '#terms_accept');
                await sleep(1000);
                await mouseMoveAndClick(page, '#terms_accept');
                await sleep(1000);
                $logger('下一步4');
                await mouseMoveAndClick(page, '#shipping-method-submit');
                $logger('等待页面跳转...');
                await page.waitForSelector('#payment-method-unionpay_b', {
                    timeout: 30000
                });

                //选择支付方式页面
                await page.waitForTimeout(4000);
                $logger('进入支付方式页面成功');
                await mouseMoveAndClick(page, '#payment-method-unionpay_b');
                await page.waitForSelector('#warning-unionpay_b .js-apm-paymentbtn', {
                    timeout: 10000
                });
                await sleep(2000);
                $logger('确认支付');
                await mouseMoveAndClick(page, '#warning-unionpay_b .js-apm-paymentbtn');
                $logger('等待下单结果...');
                await page.waitForSelector('#citconPaymentDiv .modal-body iframe', {
                    timeout: 30000
                });

                //todo:下单成功，发送通知

            } catch(e) {
                $logger('出错！', e);
            }
        }
    }

})();
